package com.cfl.springboot.config;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.sql.SQLException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.annotation.Resource.AuthenticationType;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;
import com.cfl.springboot.dao.UserMapper;

@Configuration
@PropertySource(value={"classpath:config.properties"})
public class MyBatisConfig {

	@Value("${jdbc_url}")
	private String url;
	
	@Value("${jdbc_username}")
	private String username;
	
	@Value("${jdbc_password}")
	private String password;
	
	@Value("${validationQuery}")
	private String validationQuery;
	
	@Bean(destroyMethod="close")
	public DruidDataSource dataSource()
	{			
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setInitialSize(0);		// 初始化连接大小
		dataSource.setMaxActive(20);		// 连接池最大使用连接数量
		dataSource.setMinIdle(0);			// 连接池最连接池数量
		dataSource.setMaxWait(60000);		// 获取连接最大等待时间
		
		dataSource.setValidationQuery(validationQuery);
		dataSource.setTestOnBorrow(false);
		dataSource.setTestOnReturn(false);
		dataSource.setTestWhileIdle(true);

		dataSource.setTimeBetweenEvictionRunsMillis(600000);	// 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
		dataSource.setMinEvictableIdleTimeMillis(25200000);    	// 配置一个连接在池中最小生存的时间，单位是毫秒
		dataSource.setRemoveAbandoned(true);					// 打开removeAbandoned功能
		dataSource.setRemoveAbandonedTimeout(1800);				// 1800秒，也就是30分钟
		dataSource.setLogAbandoned(true);						// 关闭abanded连接时输出错误日志
		
		return dataSource;
	}
	
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
		
		// 设置数据源
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource());
		
		// 设置mybatis的主配置文件
		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/cfl/springboot/mapping/*.xml"));
		
		return sqlSessionFactoryBean;
	}
}
